package com.czmh.etc.onlinepubsys.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.configuration.WxAppletConfig;
import com.czmh.etc.onlinepubsys.constants.cmg.BusinessType;
import com.czmh.etc.onlinepubsys.dto.EtcOrderListDTO;
import com.czmh.etc.onlinepubsys.dto.EtcOrderListParam;
import com.czmh.etc.onlinepubsys.entity.mingchuang.EtcOrder;
import com.czmh.etc.onlinepubsys.entity.mingchuang.*;
import com.czmh.etc.onlinepubsys.enums.cmg.ApiCodeEnum;
import com.czmh.etc.onlinepubsys.json.JsonResult;
import com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult;
import com.czmh.etc.onlinepubsys.jy.utils.Query;
import com.czmh.etc.onlinepubsys.model.*;
import com.czmh.etc.onlinepubsys.entity.wj.EtcWjOrder;
import com.czmh.etc.onlinepubsys.queue.AutoCancelTimeOutOrderListener;
import com.czmh.etc.onlinepubsys.queue.RedisDelayedQueue;
import com.czmh.etc.onlinepubsys.request.cmg.CancelBusinessRequest;
import com.czmh.etc.onlinepubsys.request.mingchuang.EtcOrderStateRequest;
import com.czmh.etc.onlinepubsys.request.mingchuang.WechatNotifyRespone;
import com.czmh.etc.onlinepubsys.request.ue.CancelOrderRequest;
import com.czmh.etc.onlinepubsys.response.cmg.ApiResponseBase;
import com.czmh.etc.onlinepubsys.response.ue.ApiResponse;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.EtcPayOrderService;
import com.czmh.etc.onlinepubsys.services.EtcUserInfoSevice;
import com.czmh.etc.onlinepubsys.services.SysConfigService;
import com.czmh.etc.onlinepubsys.services.mingchuang.*;
import com.czmh.etc.onlinepubsys.services.wj.WjIEtcOrderService;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import com.czmh.etc.onlinepubsys.utils.WeiXinPayUtils;
import com.czmh.etc.onlinepubsys.utils.cmg.CmgHttpUtil;
import com.czmh.etc.onlinepubsys.utils.mingchuang.PayUtil;
import com.czmh.etc.onlinepubsys.utils.ue.UeHttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/{version}/api/order/deposit")
@Api(tags = "ETC订金订单接口")
public class EtcDepositOrderController {
    @Value("${spring.profiles.active}")
    private String profile;

    @Autowired
    private WxAppletConfig config;

    @Autowired
    private IEtcOrderService etcOrderService;
    @Autowired
    private WjIEtcOrderService wjEtcOrderService;
    @Autowired
    private IWechatService wechatService;
    @Autowired
    private ICurrentContextService currentContextService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IExchangeCodeService exchangeCodeService;
    @Autowired
    private EtcOrderService etcOrderServicee;
    @Autowired
    private EtcUserInfoSevice etcUserInfoSevice;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private EtcPayOrderService etcPayOrderService;
    @Autowired
    private EtcOrderService orderService;
    @Autowired
    private IEtcApplyService etcApplyService;
    @Autowired
    private ICarInfoService carInfoService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private RedisDelayedQueue redisDelayedQueue;

    @Value("${cmg.accessno}")
    private String accessno;

    @PostMapping("/createUnPayOrder")
    @ApiOperation("微信创建待支付订单")
    public JSONResult createUnPayOrder(@RequestBody EtcOrder entity) {
        log.info("微信创建待支付订单:{}", JSON.toJSONString(entity));
        if (entity == null || StringUtils.isEmpty(entity.getUserId())) {
            JSONResult result = new JSONResult();
            result.setCode(JSONResult.FAIL);
            result.setMessage("请提交正确用户信息！");
            return result;
        }
        // 手机号+验证码登录
        String redisValidCode = String.valueOf(redisUtil.get(entity.getPhone()));
        if (StringUtils.isNotEmpty(entity.getValidCode()) && StringUtils.isNotEmpty(redisValidCode)
                && (entity.getValidCode().equals(redisValidCode))) {
            if ((redisUtil.get("unCheckPhoneList") != null ? String.valueOf(redisUtil.get("unCheckPhoneList")) : "").indexOf(entity.getPhone()) == -1) {
                // 注销验证码
                redisUtil.del(entity.getPhone());
            }
        } else {
            JSONResult result = new JSONResult();
            result.setCode(JSONResult.FAIL);
            result.setMessage("手机验证码不正确！");
            return result;
        }

        JSONResult result = new JSONResult();

        //如果用户存在且手机号码跟收货手机号码不同则根据收货手机号码创建新用户信息
        EtcUser e = etcUserInfoSevice.queryUserInfo(entity.getUserId());
        if (null == e) {
            EtcUser user = new EtcUser();
            user.setUser_id(Sequence.getId());
            user.setCreate_time(new Date());
            user.setUpdate_time(new Date());
            user.setUser_sex(1);
            user.setUser_status(0);
            // 1.初始化ETC用户信息
            etcUserInfoSevice.insert(user);
        } else if (StringUtils.isNotEmpty(e.getUser_phone()) && !e.getUser_phone().equalsIgnoreCase(entity.getPhone())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("该手机号码已经绑定其他ETC！");
            return result;
        }

        String userId = entity.getUserId();

        CurrentContext ctx = currentContextService.getByUserId(userId);

        if (ctx != null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("请先激活之前申请的设备");
            return result;
        }


        String orderNo = PayUtil.generateOrderNo();

        log.info("保存订单:{}", orderNo);
        //记录当前进行时信息
        int payState = 0; //默认是未付款

        entity.setPayType(0); //微信支付
        entity.setOrderNo(orderNo);
        entity.setAmount(0);
        entity.setPayState(payState);
        entity.setBody("");
        entity.setState(0);

        ctx = new CurrentContext();
        ctx.setUserId(userId);
        ctx.setOrderNo(orderNo);
        ctx.setState(payState);
        ctx.setPayMode(entity.getPayMode());
        etcOrderService.saveOrderAndContext(entity, ctx, null);
        result.setCode(JSONResult.SUCCESS);
        return result;
    }


    @PostMapping("/createPayOrderByCode")
    @ApiOperation("兑换码支付订单")
    public JSONResult createPayOrderByCode(@RequestBody EtcOrder entity) {
        log.info("兑换码支付订单:{}", JSON.toJSONString(entity));

        JSONResult result = new JSONResult();

        //格式化兑换码
        if (entity.getCode() == null) {
            result.setCode(JSONResult.FAIL);
            log.info("兑换码为空:{}", entity.getCode());
            result.setMessage("兑换码不能为空");
            return result;
        } else {
            entity.setCode(entity.getCode().trim());
        }

        String userId = entity.getUserId();

        CurrentContext ctx = currentContextService.getByUserId(userId);

        if (ctx == null || ctx.getState() != 4) {
            result.setCode(JSONResult.FAIL);
            log.info("用户没有申请流程");
            result.setMessage("请完善用户车辆和签约信息");
            return result;
        }
        Device device = deviceService.get(entity.getDvId());
        if (device == null) {
            JsonResult r = new JsonResult();
            JSONObject jsonObject = new JSONObject();
            int state = etcOrderServicee.isExistProductSn(entity.getDvId());
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("productSn", entity.getDvId());
            EtcDevice etcDevice = etcOrderServicee.queryObject(queryMap);
            //判断产品编码对应的产品是否存在
            if (state == 0 || etcDevice == null) {
                result.setCode(JSONResult.FAIL);
                log.info("产品不存在:{}", entity.getDvId());
                result.setMessage("产品不存在");
                jsonObject.put("state", 0);
                jsonObject.put("etcDevice", null);
                result.setRspData(JSON.toJSONString(jsonObject));
                return result;
            } else {
                //产品存在需要判断产品是否被支付
                Integer count = etcOrderServicee.queryEtcPayState(entity.getDvId(), 1, 1);
                if (count == null || count.intValue() == 0) {
                    //检查兑换码有效性
                    String code = entity.getCode();
                    if (!exchangeCodeService.checkExchangeCode(code, null)) {
                        result.setCode(JSONResult.FAIL);
                        log.info("该兑换码不可使用:{}", code);
                        result.setMessage("该兑换码不可使用！");
                        return result;
                    }
                    //兑换码支付成功则更新订单状态和产品编码到订单记录中
                    entity.setAmount(etcDevice.getSaleMoney().multiply(new BigDecimal(100)).intValue());
                    entity.setBody(etcDevice.getProductSn());
                    entity.setPayType(1); //兑换码
                    entity.setPayNo(code);
                    entity.setPayState(1);
                    entity.setOrderNo(ctx.getOrderNo());
                    EtcOrder e = etcOrderService.getByOrderNo(ctx.getOrderNo());
                    entity.setId(e.getId());
                    etcOrderService.updateByObject(entity);
                    return result;
                } else {
                    result.setCode(JSONResult.FAIL);
                    log.info("产品不可用!:{}", entity.getDvId());
                    result.setMessage("产品不可用");
                    jsonObject.put("state", 2);
                    jsonObject.put("etcDevice", null);
                    result.setRspData(JSON.toJSONString(jsonObject));
                    return result;
                }
            }
        }
        //产品存在需要判断产品是否被支付
        Integer count = etcOrderServicee.queryEtcPayState(entity.getDvId(), 1);
        if (count != null && count.intValue() == 1) {
            JSONObject jsonObject = new JSONObject();
            result.setCode(JSONResult.FAIL);
            result.setMessage("产品不可用");
            log.info("产品不可用!!:{}", entity.getDvId());
            jsonObject.put("state", 2);
            return result;
        }
        //检查兑换码有效性
        String code = entity.getCode();
        if (!exchangeCodeService.checkExchangeCode(code, null)) {
            log.info("不支持兑换该产品:{}", code);
            result.setCode(JSONResult.FAIL);
            result.setMessage("不支持兑换该产品");
            return result;
        }

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("deleteFlag", "0");
        queryMap.put("productSn", entity.getDvId());
        EtcDevice etcDevice = etcOrderServicee.queryObject(queryMap);
        //兑换码支付成功则更新订单状态和产品编码到订单记录中
        entity.setAmount(etcDevice.getSaleMoney().multiply(new BigDecimal(100)).intValue());
        entity.setBody(etcDevice.getProductSn());
        entity.setPayType(1); //兑换码
        entity.setPayNo(code);
        entity.setPayState(1);
        EtcOrder e = etcOrderService.getByOrderNo(ctx.getOrderNo());
        entity.setId(e.getId());
        etcOrderService.updateByObject(entity);

        return result;
    }

    @PostMapping("/createPayOrder")
    @ApiOperation("微信创建支付订单")
    public JSONResult createPayOrder(@RequestBody EtcOrder entity) {
        log.info("微信创建支付订单:{}", JSON.toJSONString(entity));
        //产品存在需要判断产品是否被支付
        Integer count = etcOrderServicee.queryEtcPayState(entity.getDvId(), 1);
        if (count != null && count.intValue() == 1) {
            JSONResult result = new JSONResult();
            JSONObject jsonObject = new JSONObject();
            result.setCode(JSONResult.FAIL);
            result.setMessage("产品不可用");
            jsonObject.put("state", 2);
            return result;
        }

        JSONResult result = new JSONResult();

        String userId = entity.getUserId();

        CurrentContext ctx = currentContextService.getByUserId(userId);

        if (ctx == null || ctx.getState() != 4) {
            result.setCode(JSONResult.FAIL);
            log.info("用户没有申请流程");
            result.setMessage("请完善用户车辆和签约信息");
            return result;
        }

        Device device = deviceService.get(entity.getDvId());
        //接入新库存需要判断库存逻辑
        if (device == null) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("productSn", entity.getDvId());
            EtcDevice etcDevice = etcOrderServicee.queryObject(queryMap);
            if (null != etcDevice) {
                Device device1 = new Device();
                device1.setAmount(etcDevice.getSaleMoney().multiply(new BigDecimal(100)).intValue());
                device1.setName(etcDevice.getProductSn());
                device = device1;
            }
        }
        if (device == null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("请正确选择你要的设备");
            return result;
        }

//        String orderNo = PayUtil.generateOrderNo();
        String orderNo = ctx.getOrderNo();
        String body = device.getName();
        Integer amount = device.getAmount();

        if ("dev".equals(profile) || "test".equals(profile)) { //测试环境付款1分钱
            amount = 1;
        }
        //调用微信支付下单
        log.info("微信支付下单,订单号:{},设备价格:{}", orderNo, amount);

        result = wechatService.unifiedOrder(entity.getOpenId(), orderNo, body, amount);

        if (JSONResult.SUCCESS.equals(result.getCode())) {
            log.info("保存订单:{}", orderNo);
            //记录当前进行时信息
            int payState = 0; //默认是未付款

            entity.setPayType(0); //微信支付
            entity.setAmount(amount);
            entity.setPayState(payState);
            entity.setBody(body);
            EtcOrder order = etcOrderService.getByOrderNo(ctx.getOrderNo());
            entity.setId(order.getId());
            etcOrderService.updateByObject(entity);
        }
        return result;
    }

    @PostMapping("/createDepositOrder")
    @ApiOperation("微信创建订金支付订单")
    public JSONResult createDepositOrder(@RequestBody EtcOrder entity) {
        log.info("微信创建订金支付订单:{}", JSON.toJSONString(entity));
        //判断是否在流程当中且符合支付订金订单条件
        CurrentContext ctx = currentContextService.getByUserId(entity.getUserId());
        if (ctx == null || ctx.getState() != 4) {
            JSONResult result = new JSONResult();
            result.setCode(JSONResult.FAIL);
            log.info("用户没有申请流程");
            result.setMessage("请完善用户车辆和签约信息");
            return result;
        }

        Device device = deviceService.get(entity.getDvId());
        //接入新库存需要判断库存逻辑
        if (device == null) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("productSn", entity.getDvId());
            EtcDevice etcDevice = etcOrderServicee.queryObject(queryMap);
            if (null != etcDevice) {
                Device device1 = new Device();
                device1.setAmount(etcDevice.getSaleMoney().multiply(new BigDecimal(100)).intValue());
                device1.setName(etcDevice.getProductSn());
                device = device1;
            }
        }
        if (device == null) {
            JSONResult result = new JSONResult();
            result.setCode(JSONResult.FAIL);
            result.setMessage("请正确选择你要的设备");
            return result;
        }

        String orderNo = PayUtil.generateOrderNo();

        String body = device.getName();
        Integer amount = device.getAmount();
        //获取双片押金价格-招商渠道
        if (entity.getType() == 3) {
            SysConfig doubleAmount = sysConfigService.queryByKey("double_amount");
            if (doubleAmount != null && doubleAmount.getConfigValue() != null && StringUtils.isNotEmpty(doubleAmount.getConfigValue())) {
                String value = doubleAmount.getConfigValue();
                amount = Integer.valueOf(value);
            } else {
                JSONResult result = new JSONResult();
                result.setMessage("系统缺少配置信息，请联系管理员！");
                result.setCode(JSONResult.FAIL);
                return result;
            }
        }
        //获取单片押金价格-招商渠道单片和联合渠道单片
        if (entity.getType() == 4 || entity.getType() == 5) {
            SysConfig simpleAmount = sysConfigService.queryByKey("simple_amount");
            if (simpleAmount != null && simpleAmount.getConfigValue() != null && StringUtils.isNotEmpty(simpleAmount.getConfigValue())) {
                String value = simpleAmount.getConfigValue();
                amount = Integer.valueOf(value);
            } else {
                JSONResult result = new JSONResult();
                result.setMessage("系统缺少配置信息，请联系管理员！");
                result.setCode(JSONResult.FAIL);
                return result;
            }
        }

        if ("dev".equals(profile) || "test".equals(profile)) { //测试环境付款1分钱
            amount = 1;
        }
        //调用微信支付下单
        log.info("微信支付下单,订单号:{},设备价格:{}", orderNo, amount);

        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getPayState, 0);
        lambda.eq(EtcPayOrder::getOrderSn, entity.getOrderNo());
        EtcPayOrder etcPayOrder = etcPayOrderService.getOne(wrapper, true);

        JSONResult result = new JSONResult();
        result = wechatService.unifiedDepositOrder(entity.getOpenId(), orderNo, body, amount);

        if (JSONResult.SUCCESS.equals(result.getCode())) {
            log.info("保存订金支付订单:{}", orderNo);
            if (etcPayOrder == null) {
                EtcPayOrder order = new EtcPayOrder();
                order.setId(Sequence.getId());
                order.setAmount(amount);
                order.setCity(entity.getCity());
                order.setRegion(entity.getRegion());
                order.setConsigneeName(entity.getConsignee());
                order.setConsigneePhone(entity.getPhone());
                order.setPhone(entity.getPhone());
                order.setDetailAddress(entity.getAddress());
                order.setOpenid(entity.getOpenId());
                order.setUserId(entity.getUserId());
                order.setOrderSn(entity.getOrderNo());
                order.setChanelType(entity.getType());
                order.setOrderNo(orderNo);
                order.setVehiclePlate(entity.getVehPlate());
                order.setVehicleColor(entity.getVehColor());
                order.setCreateTime(new Date());
                order.setUpdatedTime(new Date());
                etcPayOrderService.save(order);
            } else {
                etcPayOrder.setUpdatedTime(new Date());
                etcPayOrder.setOrderNo(orderNo);
                etcPayOrderService.updateById(etcPayOrder);
            }
        }
        return result;
    }

    @PostMapping("/createUnitePayOrder")
    @ApiOperation("前装ETC权益包支付订单")
    public JSONResult createUnitePayOrder(@RequestBody EtcOrder entity) {
        log.info("前装ETC权益包支付订单:{}", JSON.toJSONString(entity));
        JSONResult result = new JSONResult();
        String orderNo = PayUtil.generateOrderNo();

        String body = entity.getName();
        Integer amount = 0;

        SysConfig simpleAmount = new SysConfig();
        if (entity.getEquityType() == 0) {
            simpleAmount = sysConfigService.queryByKey("eq_amount");
        } else {
            simpleAmount = sysConfigService.queryByKey("eq_amount2");
        }
        if (simpleAmount != null && simpleAmount.getConfigValue() != null && StringUtils.isNotEmpty(simpleAmount.getConfigValue())) {
            String value = simpleAmount.getConfigValue();
            amount = Integer.valueOf(value);
        } else {
            result.setMessage("系统缺少配置信息，请联系管理员!！");
            result.setCode(JSONResult.FAIL);
            return result;
        }

        EtcPayOrder etcPayOrder = null;
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getPayState, 0);
        lambda.eq(EtcPayOrder::getType, 2);
        lambda.eq(EtcPayOrder::getUserId, entity.getUserId());
        lambda.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list = etcPayOrderService.list(wrapper);
        Date currentDate = new Date();
        for (int i = 0; i < list.size(); i++) {
            EtcPayOrder payOrder = list.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            } else {
                etcPayOrder = payOrder;
            }
        }

        if (JSONResult.SUCCESS.equals(result.getCode())) {
            log.info("前装ETC权益包支付订单:{}", orderNo);
        }

        if (etcPayOrder == null) {
            result = wechatService.unifiedDepositOrder(entity.getOpenId(), orderNo, body, amount);
            EtcPayOrder order = new EtcPayOrder();
            order.setId(Sequence.getId());
//            order.setEtcSn("54012200" + entity.getEtcSn());
            order.setAmount(amount);
            order.setPhone(entity.getPhone());
            order.setProductSn(entity.getDvId());
            order.setOpenid(entity.getOpenId());
            order.setUserId(entity.getUserId());
            order.setChanelType(entity.getType());
            order.setOrderNo(orderNo);
            order.setPayType(0);
            order.setOrderSn(orderNo);
            order.setType(8);
            order.setIspayType(0);
            order.setRemark(orderNo);
            order.setConsigneeName(entity.getConsignee());
            order.setConsigneePhone(entity.getPhone());
            order.setProvince(entity.getProvince());
            order.setCity(entity.getCity());
            order.setDetailAddress(entity.getAddress());
            order.setCreateTime(currentDate);
            order.setUpdatedTime(currentDate);
            order.setCustomer(entity.getCustomer());
            order.setProName(entity.getProName());
            //请求信息附加到扩展字段
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("unifiedDepositOrder", JSON.toJSONString(result));
            order.setJsonData(jsonObject.toJSONString());
            etcPayOrderService.save(order);

            SysConfig orderOverTime = sysConfigService.queryByKey("order_over_time");
            int orderOverTimes = 1800;
            if (orderOverTime != null && orderOverTime.getConfigValue() != null && StringUtils.isNotEmpty(orderOverTime.getConfigValue())) {
                String value = orderOverTime.getConfigValue();
                orderOverTimes = Integer.valueOf(value);
            }
            //获取订单超时时间
            redisDelayedQueue.addQueue(order.getId(), orderOverTimes, TimeUnit.SECONDS, AutoCancelTimeOutOrderListener.class.getName());

        } else {
            if (etcPayOrder.getJsonData() != null) {
                JSONObject o = JSON.parseObject(etcPayOrder.getJsonData());
                if (o != null && o.getString("unifiedDepositOrder") != null) {
                    result = JSON.parseObject(o.getString("unifiedDepositOrder"), JSONResult.class);
                }
            }
            etcPayOrder.setUpdatedTime(new Date());
            etcPayOrderService.updateById(etcPayOrder);
        }

        return result;
    }

    @PostMapping("/queryUnitePayOrderList")
    @ApiOperation(value = "获取前装ETC权益包订单列表", response = EtcOrderListDTO.class)
    public JSONResult queryUnitePayOrderList(@RequestBody EtcOrderListParam param) {
        JSONResult result = new JSONResult();
        result.setCode(JSONResult.SUCCESS);
        if (StringUtils.isEmpty(param.getUserId())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("用户userId不能为空");
            return result;
        }

        //以下搜索出某一用户的所待支付订单，同时逻辑删除超过30分钟的订单
        QueryWrapper<EtcPayOrder> wrapper3 = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda3 = wrapper3.lambda();
        lambda3.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda3.eq(EtcPayOrder::getPayState, 0);
        lambda3.eq(EtcPayOrder::getType, 8);
        lambda3.eq(EtcPayOrder::getUserId, param.getUserId());
        lambda3.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list3 = etcPayOrderService.list(wrapper3);
        Date currentDate = new Date();
        for (int i = 0; i < list3.size(); i++) {
            EtcPayOrder payOrder = list3.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            }
        }

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("userId", param.getUserId());
        queryMap.put("page", param.getPageNum());
        queryMap.put("limit", param.getPageSize());
        Query query = new Query(queryMap);

        Page<EtcPayOrder> page = new Page<>(param.getPageNum(), param.getPageSize());
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getUserId, param.getUserId());
        lambda.eq(EtcPayOrder::getType, 8);
        lambda.orderByDesc(EtcPayOrder::getCreateTime);
        IPage<EtcPayOrder> r = etcPayOrderService.page(page, wrapper);
        result.setRspData(JSON.toJSONString(r.getRecords()));
        return result;
    }

    @PostMapping("/getUnitePayOrderDetail")
    @ApiOperation(value = "获取前装ETC权益包支付订单详情", response = EtcPayOrder.class)
    public JSONResult getUnitePayOrderDetail(@RequestBody EtcOrder entity) {
        JSONResult result = new JSONResult();
        if (StringUtils.isEmpty(entity.getOrderNo())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单号不能为空!");
            return result;
        }
        //以下搜索出某一用户的所待支付订单，同时逻辑删除超过30分钟的订单
        QueryWrapper<EtcPayOrder> wrapper3 = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda3 = wrapper3.lambda();
        lambda3.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda3.eq(EtcPayOrder::getPayState, 0);
        lambda3.eq(EtcPayOrder::getType, 8);
        lambda3.eq(EtcPayOrder::getUserId, entity.getUserId());
        lambda3.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list3 = etcPayOrderService.list(wrapper3);
        Date currentDate = new Date();
        for (int i = 0; i < list3.size(); i++) {
            EtcPayOrder payOrder = list3.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            }
        }
        //获取订金订单详情
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getOrderSn, entity.getOrderNo());
        EtcPayOrder etcPayOrder = etcPayOrderService.getOne(wrapper, true);
        if (etcPayOrder != null) {
            result.setCode(JSONResult.SUCCESS);
            result.setRspData(JSON.toJSONString(etcPayOrder));
        } else {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单详情不存在");
        }
        return result;
    }


    @PostMapping("/createEquityPayOrder")
    @ApiOperation("微信创建权益包支付订单")
    public JSONResult createEquityPayOrder(@RequestBody EtcOrder entity) {
        entity.setType(7);
        log.info("微信创建权益包支付订单:{}", JSON.toJSONString(entity));
        Device device = deviceService.get("54012200" + entity.getEtcSn());
        //接入新库存需要判断库存逻辑
        if (device == null) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("productSn", entity.getDvId());
            EtcDevice etcDevice = etcOrderServicee.queryObject(queryMap);
            if (null != etcDevice) {
                Device device1 = new Device();
                device1.setAmount(etcDevice.getSaleMoney().multiply(new BigDecimal(100)).intValue());
                device1.setName(etcDevice.getProductSn());
                device = device1;
            }
        }
        if (device == null) {
            JSONResult result = new JSONResult();
            result.setCode(JSONResult.FAIL);
            result.setMessage("请正确选择你要的设备");
            return result;
        }

        String orderNo = PayUtil.generateOrderNo();

        String body = device.getName();
        Integer amount = device.getAmount();

        //获取单片押金价格-招商渠道单片和联合渠道单片
        if (entity.getType() == 7) {
            SysConfig simpleAmount = new SysConfig();
            if (entity.getEquityType() == 0) {
                simpleAmount = sysConfigService.queryByKey("equity_amount");
            } else {
                simpleAmount = sysConfigService.queryByKey("equity_amount2");
            }
            if (simpleAmount != null && simpleAmount.getConfigValue() != null && StringUtils.isNotEmpty(simpleAmount.getConfigValue())) {
                String value = simpleAmount.getConfigValue();
                amount = Integer.valueOf(value);
            } else {
                JSONResult result = new JSONResult();
                result.setMessage("系统缺少配置信息，请联系管理员!！");
                result.setCode(JSONResult.FAIL);
                return result;
            }
        }

        if ("dev".equals(profile) || "test".equals(profile)) { //测试环境付款1分钱
            amount = 1;
        }
        //调用微信支付下单
        log.info("微信创建权益包支付订单,设备号:{},设备价格:{}", "54012200" + entity.getEtcSn(), amount);

        //以下搜索出某一用户的所待支付订单，同时逻辑删除超过30分钟的订单
        EtcPayOrder etcPayOrder = null;
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getPayState, 0);
        lambda.eq(EtcPayOrder::getType, 2);
        lambda.eq(EtcPayOrder::getUserId, entity.getUserId());
        lambda.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list = etcPayOrderService.list(wrapper);
        Date currentDate = new Date();
        for (int i = 0; i < list.size(); i++) {
            EtcPayOrder payOrder = list.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            } else {
                etcPayOrder = payOrder;
            }
        }

        JSONResult result = new JSONResult();
        if (JSONResult.SUCCESS.equals(result.getCode())) {
            log.info("微信创建权益包支付订单:{}", orderNo);
            if (etcPayOrder == null) {
                result = wechatService.unifiedDepositOrder(entity.getOpenId(), orderNo, body, amount);
                EtcPayOrder order = new EtcPayOrder();
                order.setId(Sequence.getId());
                order.setEtcSn("54012200" + entity.getEtcSn());
                order.setAmount(amount);
                order.setPhone(entity.getPhone());
                order.setProductSn(entity.getDvId());
                order.setOpenid(entity.getOpenId());
                order.setUserId(entity.getUserId());
                order.setChanelType(entity.getType());
                order.setOrderNo(orderNo);
                order.setPayType(0);
                order.setOrderSn(orderNo);
                order.setType(2);
                order.setIspayType(0);
                order.setCreateTime(currentDate);
                order.setUpdatedTime(currentDate);
                //请求信息附加到扩展字段
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("unifiedDepositOrder", JSON.toJSONString(result));
                order.setJsonData(jsonObject.toJSONString());
                etcPayOrderService.save(order);

                SysConfig orderOverTime = sysConfigService.queryByKey("order_over_time");
                int orderOverTimes = 1800;
                if (orderOverTime != null && orderOverTime.getConfigValue() != null && StringUtils.isNotEmpty(orderOverTime.getConfigValue())) {
                    String value = orderOverTime.getConfigValue();
                    orderOverTimes = Integer.valueOf(value);
                }
                //获取订单超时时间
                redisDelayedQueue.addQueue(order.getId(), orderOverTimes, TimeUnit.SECONDS, AutoCancelTimeOutOrderListener.class.getName());

            } else {
                if (etcPayOrder.getJsonData() != null) {
                    JSONObject o = JSON.parseObject(etcPayOrder.getJsonData());
                    if (o != null && o.getString("unifiedDepositOrder") != null) {
                        result = JSON.parseObject(o.getString("unifiedDepositOrder"), JSONResult.class);
                    }
                }
                etcPayOrder.setUpdatedTime(new Date());
                etcPayOrderService.updateById(etcPayOrder);
            }
        }

        return result;
    }

    @PostMapping("/updateDepositOrder")
    @ApiOperation("领取权益购买商品，补全订单信息")
    public JSONResult updateDepositOrder(@RequestBody EtcOrder entity) {
        log.info("领取权益购买商品:{}", JSON.toJSONString(entity));
        if (StringUtils.isEmpty(entity.getOrderNo())) {
            JSONResult result = new JSONResult();
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单号不能为空!");
            return result;
        }

        String orderNo = PayUtil.generateOrderNo();

        Integer amount = 0;
        SysConfig simpleAmount = new SysConfig();
        simpleAmount = sysConfigService.queryByKey("equity_amount3");
        if (simpleAmount != null && simpleAmount.getConfigValue() != null && StringUtils.isNotEmpty(simpleAmount.getConfigValue())) {
            String value = simpleAmount.getConfigValue();
            amount = Integer.valueOf(value);
        } else {
            JSONResult result = new JSONResult();
            result.setMessage("系统缺少配置信息，请联系管理员!！");
            result.setCode(JSONResult.FAIL);
            return result;
        }

        if ("dev".equals(profile) || "test".equals(profile)) { //测试环境付款1分钱
            amount = 1;
        }

        //调用微信支付下单
        log.info("领取权益购买商品,设备号:{},设备价格:{}", "54012200" + entity.getEtcSn(), amount);

        //以下搜索出某一用户的所待支付订单，同时逻辑删除超过30分钟的订单
        EtcPayOrder etcPayOrder = null;
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getPayState, 0);
        lambda.eq(EtcPayOrder::getType, 2);
        lambda.eq(EtcPayOrder::getUserId, entity.getUserId());
        lambda.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list = etcPayOrderService.list(wrapper);
        Date currentDate = new Date();
        for (int i = 0; i < list.size(); i++) {
            EtcPayOrder payOrder = list.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            } else {
                etcPayOrder = payOrder;
            }
        }

        JSONResult result = new JSONResult();
        if (JSONResult.SUCCESS.equals(result.getCode())) {
            log.info("领取权益购买商品:{}", orderNo);
            if (etcPayOrder == null) {
                result = wechatService.unifiedDepositOrder(entity.getOpenId(), orderNo, entity.getEtcSn(), amount);
                EtcPayOrder order = new EtcPayOrder();
                order.setId(Sequence.getId());
                order.setEtcSn(entity.getEtcSn());
                order.setAmount(amount);
                order.setPhone(entity.getPhone());
                order.setProductSn(entity.getDvId());
                order.setOpenid(entity.getOpenId());
                order.setUserId(entity.getUserId());
                order.setChanelType(entity.getType());
                order.setOrderNo(orderNo);
                order.setPayType(0);
                order.setOrderSn(orderNo);
                order.setType(2);
                order.setRemark(entity.getOrderNo());
                order.setConsigneePhone(entity.getPhone());
                order.setProvince(entity.getProvince());
                order.setCity(entity.getCity());
                order.setDetailAddress(entity.getAddress());
                order.setCreateTime(currentDate);
                order.setUpdatedTime(currentDate);
                //请求信息附加到扩展字段
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("unifiedDepositOrder", JSON.toJSONString(result));
                order.setJsonData(jsonObject.toJSONString());
                etcPayOrderService.save(order);

                SysConfig orderOverTime = sysConfigService.queryByKey("order_over_time");
                int orderOverTimes = 1800;
                if (orderOverTime != null && orderOverTime.getConfigValue() != null && StringUtils.isNotEmpty(orderOverTime.getConfigValue())) {
                    String value = orderOverTime.getConfigValue();
                    orderOverTimes = Integer.valueOf(value);
                }
                //获取订单超时时间
                redisDelayedQueue.addQueue(order.getId(), orderOverTimes, TimeUnit.SECONDS, AutoCancelTimeOutOrderListener.class.getName());

            } else {
                if (etcPayOrder.getJsonData() != null) {
                    JSONObject o = JSON.parseObject(etcPayOrder.getJsonData());
                    if (o != null && o.getString("unifiedDepositOrder") != null) {
                        result = JSON.parseObject(o.getString("unifiedDepositOrder"), JSONResult.class);
                    }
                }
                etcPayOrder.setUpdatedTime(new Date());
                etcPayOrderService.updateById(etcPayOrder);
            }
        }
        return result;
    }


    @PostMapping("/queryPreDepositOrderList")
    @ApiOperation(value = "获取用户前置订金订单列表", response = EtcOrderListDTO.class)
    public JSONResult queryPreDepositOrderList(@RequestBody EtcOrderListParam param) {
        JSONResult result = new JSONResult();
        result.setCode(JSONResult.SUCCESS);
        if (StringUtils.isEmpty(param.getUserId())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("用户userId不能为空");
            return result;
        }

        //以下搜索出某一用户的所待支付订单，同时逻辑删除超过30分钟的订单
        QueryWrapper<EtcPayOrder> wrapper3 = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda3 = wrapper3.lambda();
        lambda3.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda3.eq(EtcPayOrder::getPayState, 0);
        lambda3.eq(EtcPayOrder::getType, 7);
        lambda3.eq(EtcPayOrder::getUserId, param.getUserId());
        lambda3.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list3 = etcPayOrderService.list(wrapper3);
        Date currentDate = new Date();
        for (int i = 0; i < list3.size(); i++) {
            EtcPayOrder payOrder = list3.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            }
        }

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("userId", param.getUserId());
        queryMap.put("page", param.getPageNum());
        queryMap.put("limit", param.getPageSize());
        Query query = new Query(queryMap);

        Page<EtcPayOrder> page = new Page<>(param.getPageNum(), param.getPageSize());
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getUserId, param.getUserId());
        lambda.eq(EtcPayOrder::getType, 7);
        lambda.orderByDesc(EtcPayOrder::getCreateTime);
        IPage<EtcPayOrder> r = etcPayOrderService.page(page, wrapper);
        result.setRspData(JSON.toJSONString(r.getRecords()));
        return result;
    }

    @PostMapping("/getPreDepositOrderDetail")
    @ApiOperation(value = "获取前置订金订单详情", response = EtcPayOrder.class)
    public JSONResult getPreDepositOrderDetail(@RequestBody EtcOrder entity) {
        JSONResult result = new JSONResult();
        if (StringUtils.isEmpty(entity.getOrderNo())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单号不能为空!");
            return result;
        }
        //以下搜索出某一用户的所待支付订单，同时逻辑删除超过30分钟的订单
        QueryWrapper<EtcPayOrder> wrapper3 = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda3 = wrapper3.lambda();
        lambda3.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda3.eq(EtcPayOrder::getPayState, 0);
        lambda3.eq(EtcPayOrder::getType, 7);
        lambda3.eq(EtcPayOrder::getUserId, entity.getUserId());
        lambda3.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list3 = etcPayOrderService.list(wrapper3);
        Date currentDate = new Date();
        for (int i = 0; i < list3.size(); i++) {
            EtcPayOrder payOrder = list3.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            }
        }
        //获取订金订单详情
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getOrderSn, entity.getOrderNo());
        EtcPayOrder etcPayOrder = etcPayOrderService.getOne(wrapper, true);
        if (etcPayOrder != null) {
            result.setCode(JSONResult.SUCCESS);
            result.setRspData(JSON.toJSONString(etcPayOrder));
        } else {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单详情不存在");
        }
        return result;
    }

    @PostMapping("/createPreDepositOrder")
    @ApiOperation("微信创建前置订金支付订单")
    public JSONResult createPreDepositOrder(@RequestBody EtcOrder entity) {
        entity.setType(7);
        log.info("微信创建前置订金支付订单:{}", JSON.toJSONString(entity));
//        Device device = deviceService.get(entity.getDvId());
//        //接入新库存需要判断库存逻辑
//        if (device == null) {
//            Map<String, Object> queryMap = new HashMap<>();
//            queryMap.put("deleteFlag", "0");
//            queryMap.put("productSn", entity.getDvId());
//            EtcDevice etcDevice = etcOrderServicee.queryObject(queryMap);
//            if (null != etcDevice) {
//                Device device1 = new Device();
//                device1.setAmount(etcDevice.getSaleMoney().multiply(new BigDecimal(100)).intValue());
//                device1.setName(etcDevice.getProductSn());
//                device = device1;
//            }
//        }
//        if (device == null) {
//            JSONResult result = new JSONResult();
//            result.setCode(JSONResult.FAIL);
//            result.setMessage("请正确选择你要的设备");
//            return result;
//        }
//
//        String orderNo = PayUtil.generateOrderNo();
//
//        String body = device.getName();
//        Integer amount = device.getAmount();

        String orderNo = PayUtil.generateOrderNo();

        String body = "微信创建前置订金支付订单";
        Integer amount = 0;

        //获取单片押金价格-招商渠道单片和联合渠道单片
        if (entity.getType() == 7) {
            SysConfig simpleAmount = sysConfigService.queryByKey("pre_simple_amount");
            if (simpleAmount != null && simpleAmount.getConfigValue() != null && StringUtils.isNotEmpty(simpleAmount.getConfigValue())) {
                String value = simpleAmount.getConfigValue();
                amount = Integer.valueOf(value);
            } else {
                JSONResult result = new JSONResult();
                result.setMessage("系统缺少配置信息，请联系管理员!！");
                result.setCode(JSONResult.FAIL);
                return result;
            }
        }

        if ("dev".equals(profile) || "test".equals(profile)) { //测试环境付款1分钱
            amount = 1;
        }
        //调用微信支付下单
        log.info("前置订金微信支付下单,设备号:{},设备价格:{}", entity.getDvId(), amount);

        //以下搜索出某一用户的所待支付订单，同时逻辑删除超过30分钟的订单
        EtcPayOrder etcPayOrder = null;
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getPayState, 0);
        lambda.eq(EtcPayOrder::getType, 7);
        lambda.eq(EtcPayOrder::getUserId, entity.getUserId());
        lambda.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list = etcPayOrderService.list(wrapper);
        Date currentDate = new Date();
        for (int i = 0; i < list.size(); i++) {
            EtcPayOrder payOrder = list.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            } else {
                etcPayOrder = payOrder;
            }
        }

        JSONResult result = new JSONResult();
        if (JSONResult.SUCCESS.equals(result.getCode())) {
            log.info("保存前置订金支付订单:{}", orderNo);
            if (etcPayOrder == null) {
                result = wechatService.unifiedDepositOrder(entity.getOpenId(), orderNo, body, amount);
                EtcPayOrder order = new EtcPayOrder();
                order.setId(Sequence.getId());
                order.setAmount(amount);
                order.setPhone(entity.getPhone());
//                order.setProductSn(entity.getDvId());
                order.setOpenid(entity.getOpenId());
                order.setUserId(entity.getUserId());
                order.setChanelType(entity.getType());
                order.setOrderNo(orderNo);
                order.setPayType(0);
                order.setOrderSn(orderNo);
                order.setType(7);
                order.setVehiclePlate(entity.getVehPlate());
                order.setConsigneePhone(entity.getPhone());
                order.setConsigneeName(entity.getConsignee());
                order.setProvince(entity.getProvince());
                order.setCity(entity.getCity());
                order.setDetailAddress(entity.getAddress());
                order.setCreateTime(currentDate);
                order.setUpdatedTime(currentDate);
                //请求信息附加到扩展字段
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("unifiedDepositOrder", JSON.toJSONString(result));
                order.setJsonData(jsonObject.toJSONString());
                etcPayOrderService.save(order);

                SysConfig orderOverTime = sysConfigService.queryByKey("order_over_time");
                int orderOverTimes = 1800;
                if (orderOverTime != null && orderOverTime.getConfigValue() != null && StringUtils.isNotEmpty(orderOverTime.getConfigValue())) {
                    String value = orderOverTime.getConfigValue();
                    orderOverTimes = Integer.valueOf(value);
                }
                //获取订单超时时间
                redisDelayedQueue.addQueue(order.getId(), orderOverTimes, TimeUnit.SECONDS, AutoCancelTimeOutOrderListener.class.getName());

            } else {
                if (etcPayOrder.getJsonData() != null) {
                    JSONObject o = JSON.parseObject(etcPayOrder.getJsonData());
                    if (o != null && o.getString("unifiedDepositOrder") != null) {
                        result = JSON.parseObject(o.getString("unifiedDepositOrder"), JSONResult.class);
                    }
                }
                etcPayOrder.setUpdatedTime(new Date());
                etcPayOrderService.updateById(etcPayOrder);
            }
        }
        return result;
    }

    @PostMapping("/getPayState")
    @ApiOperation("查询支付状态")
    public JSONResult getPayState(@RequestBody EtcOrderStateRequest req) {
        log.info("查询支付状态:{}", JSON.toJSONString(req));
        CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getOrderSn, ctx.getOrderNo());
        EtcPayOrder etcPayOrder = etcPayOrderService.getOne(wrapper, false);
        return wechatService.getPayState(etcPayOrder.getOrderNo());
    }

    @PostMapping("/cancelOrder")
    @ApiOperation("取消订单")
    public JSONResult cancelOrder(@RequestBody EtcOrder entity) {
        JSONResult result = new JSONResult();
        if (StringUtils.isEmpty(entity.getOrderNo())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单号不能为空!");
            return result;
        }
        EtcOrder etcOrder = etcOrderService.getByOrderNo(entity.getOrderNo());
        if (etcOrder == null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单不存在");
        }
        //判断产品编码对应的用户流程是否存在
        CurrentContext currentContext = currentContextService.getByUserId(etcOrder.getUserId());
        if (currentContext == null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("用户不在流程当中");
            return result;
        }
        //取消招商订单
        if (etcOrder.getType() == 3 || etcOrder.getType() == 5) {
            CancelBusinessRequest req = new CancelBusinessRequest();
            log.info("cancelBusiness:{}", JSON.toJSONString(req));
            log.info("cancelBusiness-currentContext:{}", JSON.toJSONString(currentContext));

            Long time = System.currentTimeMillis();
            req.setClientKey(accessno + time);
            req.setTime(time);
            req.setOrderNo(accessno + currentContext.getCarId());
            ApiResponseBase r = CmgHttpUtil.post(BusinessType.CANCEL_BUSINESS, req);
            if (r != null && (r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode()) || r.getCode().equalsIgnoreCase("ORDER_NOT_FOUND"))) {
                if (r.bizContent != null) {
                    //取消订单成功之后逻辑删除流程并物理删除订单
                    result.setRspData(r.getBizContent());
                    result.setMessage(r.getMsg());
                    currentContext.setState(6);
                    currentContext.setDeleteFlag(1);
                    currentContextService.update(currentContext);
                    EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
                    log.info("招行取消订单同步逻辑删流程单数据:{}", JSON.toJSONString(currentContext));
                    log.info("招行取消订单同步物理删除订单数据:{}", JSON.toJSONString(etcOrder));
                    log.info("招行取消订单同步重置用户数据:{}", JSON.toJSONString(etcUser));
                    etcOrder.setPayState(3);
                    etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
                    orderService.updateById(etcOrder);
                    etcUser.setUser_loginname("");
                    etcUser.setUser_phone("");
                    etcUserInfoSevice.updateUser(etcUser);
                }
                if (r.getCode().equalsIgnoreCase("ORDER_NOT_FOUND")) {
                    //取消订单成功之后逻辑删除流程并物理删除订单
                    result.setRspData(r.getBizContent());
                    result.setMessage(r.getMsg());
                    currentContext.setState(6);
                    currentContext.setDeleteFlag(1);
                    currentContextService.update(currentContext);
                    EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
                    log.info("招行取消订单同步逻辑删流程单数据:{}", JSON.toJSONString(currentContext));
                    log.info("招行取消订单同步物理删除订单数据:{}", JSON.toJSONString(etcOrder));
                    log.info("招行取消订单同步重置用户数据:{}", JSON.toJSONString(etcUser));
                    etcOrder.setPayState(3);
                    etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
                    orderService.updateById(etcOrder);
                    etcUser.setUser_loginname("");
                    etcUser.setUser_phone("");
                    etcUserInfoSevice.updateUser(etcUser);
                }
            } else {
                result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
                result.setMessage(r.getMsg());
            }
        }
        //取消联合电服订单
        if (etcOrder.getType() == 4) {
            CancelOrderRequest req = new CancelOrderRequest();
            String jsonStr = currentContext.getJsonData();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            if (jsonObject != null) {
                String submitOrderStatus = jsonObject.getString("submitOrderStatus");
                String order_id = jsonObject.getString("order_id");
                JSONObject submitOrderRequest = jsonObject.getJSONObject("SubmitOrderRequest");
                if (submitOrderStatus != null && submitOrderStatus.equalsIgnoreCase("1")) {
                    req.setCancel_reason("不想要了");
                    req.setOrder_id(order_id);
                    req.setBind_tel(submitOrderRequest.getString("bind_tel"));
                    log.info("cancelOrder:{}", JSON.toJSONString(req));
                    String token = redisUtil.queryUeToken();
                    ApiResponse r = UeHttpUtil.post(com.czmh.etc.onlinepubsys.constants.ue.BusinessType.CANCEL_ORDER, JSON.toJSONString(req), token);
                    if (r != null && r.getSuccess()) {
                        if (r.getSuccess()) {
                            result.setRspData(r.getRspData());
                            result.setMessage(r.getMsg());
                            currentContext.setState(6);
                            currentContext.setDeleteFlag(1);
                            currentContextService.update(currentContext);
                            EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
                            log.info("联合电服取消订单同步逻辑删流程单数据:{}", JSON.toJSONString(currentContext));
                            log.info("联合电服取消订单同步物理删除订单数据:{}", JSON.toJSONString(etcOrder));
                            log.info("联合电服取消订单同步重置用户数据:{}", JSON.toJSONString(etcUser));
                            etcOrder.setPayState(3);
                            etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
                            orderService.updateById(etcOrder);
                            etcUser.setUser_loginname("");
                            etcUser.setUser_phone("");
                            etcUserInfoSevice.updateUser(etcUser);
                        }
                    } else {
                        result.setCode(r != null ? r.getCode() : com.czmh.etc.onlinepubsys.json.cmg.JSONResult.FAIL);
                        result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
                    }
                } else {
                    currentContext.setState(6);
                    currentContext.setDeleteFlag(1);
                    currentContextService.update(currentContext);
                    EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
                    log.info("联合电服取消订单同步逻辑删流程单数据:{}", JSON.toJSONString(currentContext));
                    log.info("联合电服取消订单同步物理删除订单数据:{}", JSON.toJSONString(etcOrder));
                    log.info("联合电服取消订单同步重置用户数据:{}", JSON.toJSONString(etcUser));
                    etcOrder.setPayState(3);
                    etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
                    orderService.updateById(etcOrder);
                    etcUser.setUser_loginname("");
                    etcUser.setUser_phone("");
                    etcUserInfoSevice.updateUser(etcUser);
                }
            } else {
                currentContext.setState(6);
                currentContext.setDeleteFlag(1);
                currentContextService.update(currentContext);
                EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
                log.info("联合电服取消订单同步逻辑删流程单数据:{}", JSON.toJSONString(currentContext));
                log.info("联合电服取消订单同步物理删除订单数据:{}", JSON.toJSONString(etcOrder));
                log.info("联合电服取消订单同步重置用户数据:{}", JSON.toJSONString(etcUser));
                etcOrder.setPayState(3);
                etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
                orderService.updateById(etcOrder);
                etcUser.setUser_loginname("");
                etcUser.setUser_phone("");
                etcUserInfoSevice.updateUser(etcUser);
            }
        }
        return result;
    }

    @PostMapping("/queryDepositOrderList")
    @ApiOperation(value = "获取用户订金订单列表", response = EtcOrderListDTO.class)
    public JSONResult queryDepositOrderList(@RequestBody EtcOrderListParam param) {
        JSONResult result = new JSONResult();
        result.setCode(JSONResult.SUCCESS);
        if (StringUtils.isEmpty(param.getUserId())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("用户userId不能为空");
            return result;
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("userId", param.getUserId());
        queryMap.put("page", param.getPageNum());
        queryMap.put("limit", param.getPageSize());
        Query query = new Query(queryMap);
        List<EtcOrderListDTO> etcOrderListDTOS = etcPayOrderService.queryOrderList(query);
        result.setRspData(JSON.toJSONString(etcOrderListDTOS));
        return result;
    }

    @PostMapping("/getDepositOrderDetail")
    @ApiOperation(value = "获取订金订单详情", response = EtcPayOrder.class)
    public JSONResult getDepositOrderDetail(@RequestBody EtcOrder entity) {
        JSONResult result = new JSONResult();
        if (StringUtils.isEmpty(entity.getOrderNo())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单号不能为空!");
            return result;
        }
        //获取订金订单详情
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getOrderSn, entity.getOrderNo());
        EtcPayOrder etcPayOrder = etcPayOrderService.getOne(wrapper, true);
        if (etcPayOrder != null) {
            result.setCode(JSONResult.SUCCESS);
            result.setRspData(JSON.toJSONString(etcPayOrder));
        } else {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订金订单详情不存在");
        }
        return result;
    }

    @PostMapping("/getOrderDetail")
    @ApiOperation(value = "获取订单详情", response = EtcPayOrder.class)
    public JSONResult getOrderDetail(@RequestBody EtcOrder entity) {
        JSONResult result = new JSONResult();
        if (StringUtils.isEmpty(entity.getOrderNo())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单号不能为空!");
            return result;
        }
        EtcOrderDetail etcOrderDetail = new EtcOrderDetail();
        etcOrderDetail.setOrderSn(entity.getOrderNo());
        //获取订金订单详情
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getOrderSn, entity.getOrderNo());
        EtcPayOrder etcPayOrder = etcPayOrderService.getOne(wrapper, true);
        etcOrderDetail.setEtcPayOrder(etcPayOrder);

        //获取订单流程信息
        CurrentContext context = currentContextService.getByOrderNo(entity.getOrderNo());
        etcOrderDetail.setContext(context);

        //获取用户申请信息
        if (context != null && context.getApplyId() != null) {
            ApplyInfo applyInfo = etcApplyService.get(context.getApplyId());
            etcOrderDetail.setApplyInfo(applyInfo);
        }

        //获取车辆信息
        if (context != null && context.getCarId() != null) {
            CarInfo carInfo = carInfoService.get(context.getCarId());
            etcOrderDetail.setCarInfo(carInfo);
        }

        //获取订单信息
        if (context != null && context.getOrderNo() != null) {
            EtcOrder etcOrder = etcOrderService.getByOrderNo(context.getOrderNo());
            etcOrderDetail.setEtcOrder(etcOrder);
        }

        result.setCode(JSONResult.SUCCESS);
        result.setRspData(JSON.toJSONString(etcOrderDetail, SerializerFeature.WriteMapNullValue));
        return result;
    }

    @PostMapping("/createWjPayOrder")
    @ApiOperation("万集ETC权益包支付订单")
    public JSONResult createWjPayOrder(@RequestBody EtcWjOrder entity) {
        log.info("万集ETC权益包支付订单:{}", JSON.toJSONString(entity));
        JSONResult result = new JSONResult();
        String orderNo = PayUtil.generateOrderNo();

        String body = entity.getName();
        Integer amount = 0;

        SysConfig simpleAmount = new SysConfig();
        //获取不同套餐金额
        simpleAmount = sysConfigService.queryByKey("wjeq_amount" + entity.getEquityType());
        if (simpleAmount != null && simpleAmount.getConfigValue() != null && StringUtils.isNotEmpty(simpleAmount.getConfigValue())) {
            String value = simpleAmount.getConfigValue();
            amount = Integer.valueOf(value);
        } else {
            result.setMessage("系统缺少配置信息，请联系管理员!！");
            result.setCode(JSONResult.FAIL);
            return result;
        }

        EtcPayOrder etcPayOrder = null;
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getPayState, 0);
        lambda.eq(EtcPayOrder::getType, 2);
        lambda.eq(EtcPayOrder::getUserId, entity.getUserId());
        lambda.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list = etcPayOrderService.list(wrapper);
        Date currentDate = new Date();
        for (int i = 0; i < list.size(); i++) {
            EtcPayOrder payOrder = list.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            } else {
                etcPayOrder = payOrder;
            }
        }

        if (JSONResult.SUCCESS.equals(result.getCode())) {
            log.info("万集ETC权益包支付订单:{}", orderNo);
        }

        if (etcPayOrder == null) {
            result = wechatService.unifiedDepositOrder(entity.getOpenId(), orderNo, body, amount);
            EtcPayOrder order = new EtcPayOrder();
            order.setId(Sequence.getId());
            order.setAmount(amount);
            order.setPhone(entity.getPhoneNo());
            order.setProductSn(entity.getDvId());
            order.setOpenid(entity.getOpenId());
            order.setUserId(entity.getUserId());
            order.setOrderNo(orderNo);
            order.setPayType(0);
            order.setOrderSn(orderNo);
            order.setType(88);
            order.setIspayType(0);
            order.setRemark(orderNo);
            order.setConsigneeName(entity.getConsigneeName());
            order.setConsigneePhone(entity.getConsigneePhone());
            order.setProvince(entity.getProvince());
            order.setCity(entity.getCity());
            order.setDetailAddress(entity.getAddress());
            order.setCreateTime(currentDate);
            order.setUpdatedTime(currentDate);
            order.setProName(entity.getProName());
            //请求信息附加到扩展字段
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("unifiedDepositOrder", JSON.toJSONString(result));
            order.setJsonData(jsonObject.toJSONString());
            etcPayOrderService.save(order);

            SysConfig orderOverTime = sysConfigService.queryByKey("order_over_time");
            int orderOverTimes = 1800;
            if (orderOverTime != null && orderOverTime.getConfigValue() != null && StringUtils.isNotEmpty(orderOverTime.getConfigValue())) {
                String value = orderOverTime.getConfigValue();
                orderOverTimes = Integer.valueOf(value);
            }
            //获取订单超时时间
            redisDelayedQueue.addQueue(order.getId(), orderOverTimes, TimeUnit.SECONDS, AutoCancelTimeOutOrderListener.class.getName());

        } else {
            if (etcPayOrder.getJsonData() != null) {
                JSONObject o = JSON.parseObject(etcPayOrder.getJsonData());
                if (o != null && o.getString("unifiedDepositOrder") != null) {
                    result = JSON.parseObject(o.getString("unifiedDepositOrder"), JSONResult.class);
                }
            }
            etcPayOrder.setUpdatedTime(new Date());
            etcPayOrderService.updateById(etcPayOrder);
        }

        return result;
    }

    @PostMapping("/queryWjPayOrderList")
    @ApiOperation(value = "获取万集ETC权益包订单列表", response = EtcOrderListDTO.class)
    public JSONResult queryWjPayOrderList(@RequestBody EtcOrderListParam param) {
        JSONResult result = new JSONResult();
        result.setCode(JSONResult.SUCCESS);
        if (StringUtils.isEmpty(param.getUserId())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("用户userId不能为空");
            return result;
        }

        //以下搜索出某一用户的所待支付订单，同时逻辑删除超过30分钟的订单
        QueryWrapper<EtcPayOrder> wrapper3 = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda3 = wrapper3.lambda();
        lambda3.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda3.eq(EtcPayOrder::getPayState, 0);
        lambda3.eq(EtcPayOrder::getType, 88);
        lambda3.eq(EtcPayOrder::getUserId, param.getUserId());
        lambda3.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list3 = etcPayOrderService.list(wrapper3);
        Date currentDate = new Date();
        for (int i = 0; i < list3.size(); i++) {
            EtcPayOrder payOrder = list3.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            }
        }

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("userId", param.getUserId());
        queryMap.put("page", param.getPageNum());
        queryMap.put("limit", param.getPageSize());
        Query query = new Query(queryMap);

        Page<EtcPayOrder> page = new Page<>(param.getPageNum(), param.getPageSize());
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getUserId, param.getUserId());
        lambda.eq(EtcPayOrder::getType, 88);
        lambda.orderByDesc(EtcPayOrder::getCreateTime);
        IPage<EtcPayOrder> r = etcPayOrderService.page(page, wrapper);
        result.setRspData(JSON.toJSONString(r.getRecords()));
        return result;
    }

    @PostMapping("/getWjPayOrderDetail")
    @ApiOperation(value = "获取万集ETC权益包支付订单详情", response = EtcPayOrder.class)
    public JSONResult getWjPayOrderDetail(@RequestBody EtcWjOrder entity) {
        JSONResult result = new JSONResult();
        if (StringUtils.isEmpty(entity.getOrderNo())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单号不能为空!");
            return result;
        }
        //以下搜索出某一用户的所待支付订单，同时逻辑删除超过30分钟的订单
        QueryWrapper<EtcPayOrder> wrapper3 = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda3 = wrapper3.lambda();
        lambda3.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda3.eq(EtcPayOrder::getPayState, 0);
        lambda3.eq(EtcPayOrder::getType, 88);
        lambda3.eq(EtcPayOrder::getUserId, entity.getUserId());
        lambda3.orderByAsc(EtcPayOrder::getCreateTime);
        List<EtcPayOrder> list3 = etcPayOrderService.list(wrapper3);
        Date currentDate = new Date();
        for (int i = 0; i < list3.size(); i++) {
            EtcPayOrder payOrder = list3.get(i);
            if (DateUtil.between(payOrder.getCreateTime(), currentDate, DateUnit.MINUTE, false) > 30) {
                payOrder.setUpdatedTime(currentDate);
                payOrder.setPayState(9);
                etcPayOrderService.updateById(payOrder);
            }
        }
        //获取订金订单详情
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getOrderSn, entity.getOrderNo());
        EtcPayOrder etcPayOrder = etcPayOrderService.getOne(wrapper, true);
        if (etcPayOrder != null) {
            result.setCode(JSONResult.SUCCESS);
            result.setRspData(JSON.toJSONString(etcPayOrder));
        } else {
            result.setCode(JSONResult.FAIL);
            result.setMessage("订单详情不存在");
        }
        return result;
    }

    /**
     * 订金订单微信支付回调方法
     *
     * @param req
     * @return
     */
    @PostMapping(value = "/notify", produces = "text/xml;charset=UTF-8")
    public String notify(HttpServletRequest req) throws Exception {
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("xml");

        SortedMap<String, String> map = WeiXinPayUtils.parseXml(req.getInputStream());
        log.info("订金订单微信支付回调:{}", map);
        if (!wechatService.checkSign(map)) {
            root.addElement("return_code").addText("FAIL");
            root.addElement("return_msg").addText("验证签名失败");
            return doc.asXML();
        }

        WechatNotifyRespone resp = new WechatNotifyRespone();
        BeanUtils.copyProperties(resp, map);

        if (resp.getReturn_code().equals("SUCCESS") && resp.getResult_code().equals("SUCCESS")) {
            String out_trade_no = resp.getOut_trade_no();
            log.info("订金订单微信支付验签成功,更新订单:{}", out_trade_no);
            QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
            LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
            lambda.eq(EtcPayOrder::getDeleteFlag, 0);
            lambda.eq(EtcPayOrder::getOrderNo, out_trade_no);
            EtcPayOrder etcPayOrder = etcPayOrderService.getOne(wrapper, false);
            if (etcPayOrder != null) {
                etcPayOrder.setPayState(1);
                etcPayOrder.setIsreceive(1);
                etcPayOrder.setIspayType(1);
                etcPayOrder.setPayTime(new Date());
                etcPayOrder.setUpdatedTime(new Date());
                etcPayOrder.setPayNo(resp.getTransaction_id());
                //订金支付成功之后把支付金额同步到订单中
                etcPayOrder.setAmount(resp.getTotal_fee());
                etcPayOrderService.updateById(etcPayOrder);

                //更新进行状态
                CurrentContext ctx = currentContextService.getByOrderNo(out_trade_no);
                if(ctx.getPayMode() == 0){
                    ctx.setState(1); //已付款
                    currentContextService.update(ctx);
                }

                //把订单对应的手机号码更新到用户信息当中
                EtcWjOrder etcOrder = wjEtcOrderService.queryByOrderNo(out_trade_no);
                EtcUser etcUser = etcUserInfoSevice.queryUserInfo(etcOrder.getUserId());
                if(etcUser != null){
                    etcUser.setUser_phone(etcOrder.getPhoneNo());
                    etcUser.setUser_loginname(etcOrder.getPhoneNo());
                    etcUserInfoSevice.updateUser(etcUser);
                }
                //同步更新设备订单
//                if(etcPayOrder.getRemark() != null){
//                    String orderNo = etcPayOrder.getRemark();
//                    QueryWrapper<EtcPayOrder> wrapperx = new QueryWrapper<>();
//                    LambdaQueryWrapper<EtcPayOrder> lambdax = wrapperx.lambda();
//                    lambdax.eq(EtcPayOrder::getDeleteFlag, 0);
//                    lambdax.eq(EtcPayOrder::getOrderNo, orderNo);
//                    EtcPayOrder etcPayOrderx = etcPayOrderService.getOne(wrapperx, false);
//                    etcPayOrderx.setIsreceive(1);
//                    etcPayOrderService.updateById(etcPayOrderx);
//                }
                root.addElement("return_code").addText("SUCCESS");
                root.addElement("return_msg").addText("OK");
            } else {
                log.error("订金订单微信支付回调无法找到对应的订单信息:{}", JSON.toJSONString(resp));
                root.addElement("return_code").addText("FAIL");
                root.addElement("return_msg").addText("支付失败");
            }
        } else {
            root.addElement("return_code").addText("FAIL");
            root.addElement("return_msg").addText("支付失败");
        }
        return doc.asXML();
    }

}
